/* @flow */

import config from '../config'
import { initProxy } from './proxy'
import { initState } from './state'
import { initRender } from './render'
import { initEvents } from './events'
import { mark, measure } from '../util/perf'
import { initLifecycle, callHook } from './lifecycle'
import { initProvide, initInjections } from './inject'
import { extend, mergeOptions, formatComponentName } from '../util/index'

let uid = 0

export function initMixin (Vue: Class<Component>) {
  /**
   * 定义_init函数，初始化操作
   * 在new Vue({})时调用
   * 进行options合并、挂载操作
   * 在vm.$options上挂载属性
   * @param {Object} options
   */
  Vue.prototype._init = function (options?: Object) {
    const vm: Component = this
    // a uid
    vm._uid = uid++

    let startTag, endTag
    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      startTag = `vue-perf-start:${vm._uid}`
      endTag = `vue-perf-end:${vm._uid}`
      mark(startTag)
    }

    /**
     * a flag to avoid this being observed
     * 根据对该值进行判断，
     * 在对数据进行响应式处理时是否进行处理
     */
    vm._isVue = true
    /**
     * merge options
     * 对传入的options进行合并
     */
    if (options && options._isComponent) {
      // optimize internal component instantiation
      // since dynamic options merging is pretty slow, and none of the
      // internal component options needs special treatment.
      initInternalComponent(vm, options)
    } else {
      vm.$options = mergeOptions(
        resolveConstructorOptions(vm.constructor),
        options || {},
        vm
      )
    }
    /* istanbul ignore else */
    if (process.env.NODE_ENV !== 'production') {
      initProxy(vm)
    } else {
      vm._renderProxy = vm
    }
    // expose real self
    vm._self = vm
    /**
     * 初始化vm实例生命周期的函数
     * 在vm上定义挂载成员属性
     * vm.$parent、vm.$root、
     * vm.$children、vm.$refs
     * _isMounted、_isDestroyed
     */
    initLifecycle(vm)
    /**
     * 进行listeners处理
     * 定义.$on、.$off函数
     */
    initEvents(vm)
    /**
     * 在vm上定义挂载成员属性
     * $slots、$listeners、$attrs
     * _c、$createElement、$scopedSlots
     * 且调用defineReactive函数，对$attrs、$listeners响应式处理
     * 生成Dep实例，即id:0、1的两个Dep实例
     */
    initRender(vm)
    callHook(vm, 'beforeCreate')
    /**
     * 处理provide/inject选项
     * 实现依赖注入
     * 处理inject的成员并挂载到vm上
     * 且设置成响应式数据
     */
    initInjections(vm) // resolve injections before data/props
    /**
     * 依次对传入参数进行初始化处理并挂载到vm上
     * props、methods、data、computed、watch
     * 在该函数中亦对数据进行响应式处理
     * 初始化vm._watchers，vm._watchers = []
     * src\core\instance\state.js
     */
    initState(vm)
    /**
     * 处理provide/inject选项
     * 实现依赖注入
     * 处理provide的成员并挂载到vm上
     */
    initProvide(vm) // resolve provide after data/props
    callHook(vm, 'created')

    /* istanbul ignore if */
    if (process.env.NODE_ENV !== 'production' && config.performance && mark) {
      vm._name = formatComponentName(vm, false)
      mark(endTag)
      measure(`vue ${vm._name} init`, startTag, endTag)
    }

    /**
     * 判断vm.$options.el
     * 进行创建dom节点，最终挂载dom元素操作
     * src\platforms\web\entry-runtime-with-compiler.js
     * 执行web平台下定义的$mount函数
     */
    if (vm.$options.el) {
      vm.$mount(vm.$options.el)
    }
  }
}

export function initInternalComponent (vm: Component, options: InternalComponentOptions) {
  const opts = vm.$options = Object.create(vm.constructor.options)
  // doing this because it's faster than dynamic enumeration.
  const parentVnode = options._parentVnode
  opts.parent = options.parent
  opts._parentVnode = parentVnode

  const vnodeComponentOptions = parentVnode.componentOptions
  opts.propsData = vnodeComponentOptions.propsData
  opts._parentListeners = vnodeComponentOptions.listeners
  opts._renderChildren = vnodeComponentOptions.children
  opts._componentTag = vnodeComponentOptions.tag

  if (options.render) {
    opts.render = options.render
    opts.staticRenderFns = options.staticRenderFns
  }
}

export function resolveConstructorOptions (Ctor: Class<Component>) {
  let options = Ctor.options
  if (Ctor.super) {
    const superOptions = resolveConstructorOptions(Ctor.super)
    const cachedSuperOptions = Ctor.superOptions
    if (superOptions !== cachedSuperOptions) {
      // super option changed,
      // need to resolve new options.
      Ctor.superOptions = superOptions
      // check if there are any late-modified/attached options (#4976)
      const modifiedOptions = resolveModifiedOptions(Ctor)
      // update base extend options
      if (modifiedOptions) {
        extend(Ctor.extendOptions, modifiedOptions)
      }
      options = Ctor.options = mergeOptions(superOptions, Ctor.extendOptions)
      if (options.name) {
        options.components[options.name] = Ctor
      }
    }
  }
  return options
}

function resolveModifiedOptions (Ctor: Class<Component>): ?Object {
  let modified
  const latest = Ctor.options
  const sealed = Ctor.sealedOptions
  for (const key in latest) {
    if (latest[key] !== sealed[key]) {
      if (!modified) modified = {}
      modified[key] = latest[key]
    }
  }
  return modified
}
